package com.mico.example.springboot.mybatis.multi.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(
        basePackages = SecondaryDataSourceConfig.REPOSITORY_PACKAGE,
        sqlSessionFactoryRef = "secondarySqlSessionFactory"
)
public class SecondaryDataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix="spring.datasource.secondary")
    public DataSourceProperties secondaryDatasourceProperties(){
        return new DataSourceProperties();
    }


    @Bean
    @ConfigurationProperties(prefix="spring.datasource.secondary")
    DataSource secondaryDataSource() {
        return secondaryDatasourceProperties().initializeDataSourceBuilder().build();
    }




    // 精确到 secondary 目录，以便跟其他数据源隔离
    static final String REPOSITORY_PACKAGE = "com.mico.example.springboot.mybatis.multi.dao.secondary";




    @Bean(name = "secondaryTransactionManager")
    public DataSourceTransactionManager clusterTransactionManager() {
        return new DataSourceTransactionManager(secondaryDataSource());
    }

    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory clusterSqlSessionFactory()
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(secondaryDataSource());
        return sessionFactory.getObject();
    }
}